package top.lingkang.websocketlivechrome.nt;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理websocket内容
 */
@Slf4j
public class MyWebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    private static final int max=1024*3;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof BinaryWebSocketFrame) {
            for (Channel channel : MyHelper.viewerSet) {
                if (channel.id().asShortText().equals(ctx.channel().id().asShortText())) {
                    continue;
                }
                // 下发给观众
                //channel.writeAndFlush(new TextWebSocketFrame("123"));
                log.info("服务器接收到二进制消息,消息长度:[{}]", frame.content().capacity());
                ByteBuf byteBuf = Unpooled.directBuffer(frame.content().capacity());
                byteBuf.writeBytes(frame.content());
                channel.writeAndFlush(new BinaryWebSocketFrame(byteBuf));
            }
        } else {
            String message = "不支持的内容类型: " + frame.getClass().getName();
            System.out.println(message);
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        MyHelper.viewerSet.add(ctx.channel());
        System.out.println("有人加入连接，当前连接数：" + MyHelper.viewerSet.size());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        MyHelper.viewerSet.remove(ctx.channel());
        System.out.println("有人断开连接，当前连接数：" + MyHelper.viewerSet.size());
    }
}
